<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <i class="el-icon-user-solid"></i>
        <h2>用户登录</h2>
        <p>请输入您的账号信息完成登录</p>
      </div>

      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        class="login-form"
      >
        <!-- 账号输入 -->
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名/手机号/邮箱"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>

        <!-- 密码输入 -->
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>

        <!-- 滑块验证码区域 -->
        <el-form-item v-if="!sliderVerified">
          <div class="slider-verify-container">
            <div
              class="slider-track"
              :style="{ width: trackWidth + 'px' }"
            ></div>
            <div
              class="slider-handle"
              :style="{ left: handlePosition + 'px' }"
              @mousedown="startDrag"
              @touchstart="startDrag"
            >
              <i class="el-icon-rank"></i>
            </div>
            <div class="slider-text">
              {{ sliderText }}
            </div>
          </div>
        </el-form-item>

        <!-- 验证成功提示 -->
        <div v-if="sliderVerified" class="verify-success">
          <i class="el-icon-success"></i>
          <span>验证成功！短信验证码已发送</span>
        </div>

        <!-- 短信验证码区域 -->
        <el-form-item v-if="showSmsSection" prop="smsCode">
          <div class="sms-code-container">
            <el-input
              v-model="loginForm.smsCode"
              placeholder="请输入6位短信验证码"
              prefix-icon="el-icon-mobile-phone"
              maxlength="6"
              style="width: 70%"
            ></el-input>
            <el-button
              type="primary"
              @click="sendSmsCode"
              :disabled="isCounting || !isPhoneValid"
            >
              {{ countdownText }}
            </el-button>
          </div>
          <p class="sms-tip">验证码将发送到您账号绑定的手机号</p>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="loginLoading"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 状态提示 -->
      <div v-if="statusMessage" :class="statusClass">
        <i :class="statusIcon"></i>
        <span>{{ statusMessage }}</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    // 手机号验证规则
    const phoneRegex =
      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;

    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };

    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码长度不能少于6位"));
      } else {
        callback();
      }
    };

    const validateSmsCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入短信验证码"));
      } else if (value.length !== 6) {
        callback(new Error("验证码必须是6位数字"));
      } else {
        callback();
      }
    };

    return {
      loginForm: {
        username: "",
        password: "",
        smsCode: "",
      },
      loginRules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        smsCode: [{ validator: validateSmsCode, trigger: "blur" }],
      },
      // 滑块验证相关数据
      isDragging: false,
      handlePosition: 0,
      startX: 0,
      containerWidth: 0,
      maxHandlePosition: 0,
      sliderVerified: false,
      showSmsSection: false, //控制是否填短信验证码
      // 短信验证码相关数据
      isCounting: false,
      countdown: 0,
      countdownTimer: null,
      // 状态相关数据
      loginLoading: false,
      statusMessage: "",
      statusType: "", // success, error, warning
    };
  },
  computed: {
    // 滑块轨道宽度
    trackWidth() {
      return this.handlePosition;
    },
    // 滑块文本
    sliderText() {
      return this.isDragging ? "正在验证..." : "请按住滑块，拖动到最右边";
    },
    // 倒计时文本
    countdownText() {
      if (this.isCounting) {
        return `${this.countdown}秒后重发`;
      } else {
        return "发送验证码";
      }
    },
    // 手机号是否有效
    isPhoneValid() {
      const phoneRegex =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      return phoneRegex.test(this.loginForm.username);
    },
    // 状态样式类
    statusClass() {
      return {
        "status-message": true,
        "status-success": this.statusType === "success",
        "status-error": this.statusType === "error",
        "status-warning": this.statusType === "warning",
      };
    },
    // 状态图标
    statusIcon() {
      switch (this.statusType) {
        case "success":
          return "el-icon-success";
        case "error":
          return "el-icon-error";
        case "warning":
          return "el-icon-warning";
        default:
          return "el-icon-info";
      }
    },
  },
  mounted() {
    // 初始化滑块容器宽度
    this.$nextTick(() => {
      const container = this.$el.querySelector(".slider-verify-container");
      if (container) {
        this.containerWidth = container.offsetWidth;
        this.maxHandlePosition = this.containerWidth - 40; // 40是滑块的宽度
      }
    });
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  },
  methods: {
    // 开始拖动滑块
    startDrag(e) {
      //   console.log(e, 234);
      // this.sliderVerified为真则出现滑块验证码
      if (this.sliderVerified) return;

      this.isDragging = true;
      this.startX = e.type.includes("touch") ? e.touches[0].clientX : e.clientX;

      const handleMove = (moveEvent) => {
        console.log(moveEvent, 242);

        if (!this.isDragging) return;

        const currentX = moveEvent.type.includes("touch")
          ? moveEvent.touches[0].clientX
          : moveEvent.clientX;
        const deltaX = currentX - this.startX;
        let newPosition = this.handlePosition + deltaX;

        // 限制滑块移动范围
        newPosition = Math.max(
          0,
          Math.min(newPosition, this.maxHandlePosition)
        );

        this.handlePosition = newPosition;
        this.startX = currentX;

        // 验证成功条件（达到85%位置）
        if (newPosition >= this.maxHandlePosition * 0.85) {
          this.sliderVerified = true;
          this.showSmsSection = true;
          this.triggerSmsCode();
        }
      };

      const handleEnd = () => {
        this.isDragging = false;
        document.removeEventListener("mousemove", handleMove);
        document.removeEventListener("mouseup", handleEnd);
        document.removeEventListener("touchmove", handleMove);
        document.removeEventListener("touchend", handleEnd);

        // 如果没有验证成功，滑块返回起点
        if (!this.sliderVerified) {
          this.handlePosition = 0;
        }
      };

      document.addEventListener("mousemove", handleMove);
      document.addEventListener("mouseup", handleEnd);
      document.addEventListener("touchmove", handleMove);
      document.addEventListener("touchend", handleEnd);
    },

    // 触发短信验证码发送
    async triggerSmsCode() {
      try {
        // 调用后端接口发送短信验证码
        const response = await this.$axios.post("/api/auth/send-sms", {
          username: this.loginForm.username,
        });

        if (response.data.success) {
          this.showStatus("验证码已发送到您绑定的手机号", "success");
        } else {
          this.showStatus("发送失败，请检查账号信息", "error");
        }
      } catch (error) {
        this.showStatus("网络错误，请稍后重试", "error");
      }
    },

    // 发送短信验证码
    async sendSmsCode() {
      if (!this.loginForm.username) {
        this.showStatus("请输入账号", "error");
        return;
      }

      if (!this.isPhoneValid) {
        this.showStatus("请输入正确的手机号码", "error");
        return;
      }

      try {
        const response = await this.$axios.post("/api/auth/send-sms", {
          username: this.loginForm.username,
        });

        if (response.data.success) {
          this.startCountdown();
          this.showStatus("验证码发送成功", "success");
        } else {
          this.showStatus(response.data.message || "发送失败", "error");
        }
      } catch (error) {
        this.showStatus("网络错误，请检查网络连接", "error");
      }
    },

    // 开始倒计时
    startCountdown() {
      this.isCounting = true;
      this.countdown = 60;

      if (this.countdownTimer) {
        clearInterval(this.countdownTimer);
      }

      this.countdownTimer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          this.isCounting = false;
          clearInterval(this.countdownTimer);
        }
      }, 1000);
    },

    // 处理登录
    async handleLogin() {
      // 表单验证
      try {
        await this.$refs.loginFormRef.validate();
      } catch (error) {
        this.showStatus("请完善表单信息", "warning");
        return;
      }

      if (!this.sliderVerified) {
        this.showStatus("请先完成安全验证", "warning");
        return;
      }

      if (!this.loginForm.smsCode) {
        this.showStatus("请输入短信验证码", "warning");
        return;
      }

      this.loginLoading = true;

      try {
        // 调用后端登录接口
        const response = await this.$axios.post(
          "/api/auth/login",
          this.loginForm
        );

        if (response.data.success) {
          this.showStatus("登录成功！正在跳转...", "success");

          // 保存token到localStorage
          localStorage.setItem("token", response.data.token);
          localStorage.setItem(
            "userInfo",
            JSON.stringify(response.data.userInfo)
          );

          // 模拟登录成功后的跳转
          setTimeout(() => {
            this.$router.push("/dashboard");
          }, 1500);
        } else {
          this.showStatus(response.data.message || "登录失败", "error");
        }
      } catch (error) {
        this.showStatus("网络错误，请稍后重试", "error");
      } finally {
        this.loginLoading = false;
      }
    },

    // 显示状态信息
    showStatus(message, type) {
      this.statusMessage = message;
      this.statusType = type;
    },
  },
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-box {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header i {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
}

.login-header h2 {
  color: #303133;
  margin-bottom: 8px;
}

.login-header p {
  color: #909399;
  font-size: 14px;
}

.login-form {
  width: 100%;
}

.slider-verify-container {
  position: relative;
  height: 40px;
  background: #f5f7fa;
  border-radius: 20px;
  overflow: hidden;
}

.slider-track {
  position: absolute;
  height: 100%;
  background: linear-gradient(90deg, #67c23a, #409eff);
  border-radius: 20px;
  transition: width 0.3s ease;
}

.slider-handle {
  position: absolute;
  width: 40px;
  height: 40px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  cursor: grab;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  transition: all 0.2s ease;
}

.slider-handle:active {
  cursor: grabbing;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.slider-text {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  font-size: 14px;
  pointer-events: none;
}

.verify-success {
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 8px;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  color: #0369a1;
  font-size: 14px;
}

.verify-success i {
  margin-right: 8px;
  font-size: 16px;
}

.sms-code-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.sms-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.status-message {
  padding: 12px 16px;
  border-radius: 8px;
  margin-top: 16px;
  display: flex;
  align-items: center;
}

.status-success {
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  color: #0369a1;
}

.status-error {
  background: #fef2f2;
  border: 1px solid #fecaca;
  color: #dc2626;
}

.status-warning {
  background: #fffbeb;
  border: 1px solid #fed7aa;
  color: #ea580c;
}

.status-message i {
  margin-right: 8px;
  font-size: 16px;
}
</style>

/*
该Vue2登录组件实现了完整的登录验证流程，包含账号密码验证、滑块安全验证和短信验证码功能。主要特点包括：
1. **表单验证系统**：使用Element
UI的表单验证规则，确保用户名、密码和短信验证码的有效性 2.
**滑块验证组件**：实现可拖动的安全验证，达到85%阈值后自动触发短信验证码发送 3.
**短信验证码管理**：支持60秒倒计时重发功能，验证成功后自动显示短信验证区域 4.
**状态管理机制**：完整的验证状态流转，提供实时状态反馈和错误提示 5.
**Token存储系统**：登录成功后自动保存token和用户信息到localStorage
组件采用模块化设计，具有良好的用户体验和完整的错误处理机制。 */
